package com.youfang.sixthmedia.chat.service;

import java.util.ArrayList;
import java.util.LinkedList;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.gzit.common.async.AsynCallback;
import com.gzit.store.StoreManager;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.message.chat.GetUnReadMsgRequest;
import com.youfang.sixthmedia.message.chat.GetUnReadMsgResponse;
import com.youfang.sixthmedia.message.chat.SetUnReadMsgRequest;
import com.youfang.sixthmedia.message.chat.SetUnReadMsgResponse;
import com.youfang.sixthmedia.message.model.Buddy;
import com.youfang.sixthmedia.message.model.ChatItem;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;

public class BuddyMessageService extends Service {

	public static final String TAG = "BuddyMessageService";

	private LinkedList<BuddyWrapper> buddys = new LinkedList<BuddyWrapper>();

	boolean running = false;

	class BuddyWrapper {
		public boolean removed;
		public Buddy buddy;

	}

	@Override
	public IBinder onBind(Intent arg0) {

		return null;
	}

	private synchronized void reg(Buddy buddy) {

		// already existed in list,ommit it
		for (BuddyWrapper w : buddys) {
			if (w.buddy.userid == buddy.userid) {
				return;
			}
		}

		BuddyWrapper wrapper = new BuddyWrapper();
		wrapper.buddy = buddy;
		buddys.add(wrapper);

	}

	private synchronized void unreg(Buddy buddy) {

		BuddyWrapper w = null;
		for (BuddyWrapper b : buddys) {
			if (b.buddy.userid == buddy.userid) {
				w = b;
			}

		}

		if (w != null) {
			w.removed = true;
		}

	}

	Thread fetchingMessageThread = new Thread() {

		public void run() {

			while (running) {

				if (YoufangContext.isLogined()) {
					try {

						for (int i = buddys.size() - 1; i >= 0; i--) {
							BuddyWrapper w = buddys.get(i);

							// eliminate removed buddy
							if (w.removed) {
								synchronized (BuddyMessageService.this) {
									buddys.remove(w);
								}
							} else {
								fetchBuddyMsgs(w);

							}

						}

					} catch (Exception e) {
						e.printStackTrace();
						// ignore...

					}
				}

				try {
					Thread.sleep(YoufangContext.MESSAGE_POLL_INTERVAL);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}

	};

	private void fetchBuddyMsgs(final BuddyWrapper buddy) {

		GetUnReadMsgRequest req = new GetUnReadMsgRequest();
		req.setUserid(buddy.buddy.userid);

		// req.setUserid(552);

		try {
			Net.doSimpleHttpRemoter(req, new GetUnReadMsgResponse(),
					new AsynCallback<Response>() {

						@Override
						public void callback(Response r) {
							if (!r.isOk()) {
								Log.i(TAG, "获得buddy:" + buddy.buddy.username
										+ "失败，原因：" + r.getError());
								return;
							}

							GetUnReadMsgResponse resp = (GetUnReadMsgResponse) r;
							ArrayList<ChatItem> messages = resp.getDataList();
							if (messages.isEmpty()) {
								return;
							}

							notifyMessageFeteched(buddy, messages);
						}
					}).get(); // wait until finish...
		} catch (Exception e) {
			//
			e.printStackTrace();

		}

	}

	// in case we got the message list,notify server...
	private void notifyMessageFeteched(final BuddyWrapper buddy,
			final ArrayList<ChatItem> messages) {

		SetUnReadMsgRequest req = new SetUnReadMsgRequest();
		req.setUserid(buddy.buddy.userid);

		try {
			Net.doSimpleHttpRemoter(req, new SetUnReadMsgResponse(),
					new AsynCallback<Response>() {

						@Override
						public void callback(Response r) {
							if (!r.isOk()) {
								Log.i(TAG, "设置消息状态失败:" + buddy.buddy.username
										+ "失败，原因：" + r.getError());
								return;
							}

							storeAndBroadCast(buddy, messages);

						}
					}).get();
		} catch (Exception e) {// // wait until finish...
			//
			e.printStackTrace();

		}

	}

	private void storeAndBroadCast(final BuddyWrapper buddy,
			final ArrayList<ChatItem> messages) {

		new AsyncTask<String, Integer, Boolean>() {

			@Override
			protected Boolean doInBackground(String... params) {

				try {
					StoreManager.insertAll(messages);
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
				return true;
			}

			protected void onPostExecute(Boolean result) {
				// broadcast messsage...
				if (result) {
					Intent intent = new Intent();
					intent.putExtra("userid", buddy.buddy.userid);
					intent.putParcelableArrayListExtra("datalist", messages);
					intent.setAction(YoufangContext.CHAT_ATION);
					sendBroadcast(intent);
				}

			};
		}.execute("");

	}

	@Override
	public void onCreate() {
		super.onCreate();

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			String action = bundle.getString("action");
			if ("start".equals(action)) {// reg new buddy...
				if (!running && !fetchingMessageThread.isAlive()) {
					running = true;
					fetchingMessageThread.setName("buddy message fetcher");
					fetchingMessageThread.start();
				}
			} else if ("reg".equals(action)) {// reg new buddy...
				Buddy buddy = (Buddy) bundle.getSerializable("buddy");
				reg(buddy);
			} else if ("unreg".equals(action)) {
				Buddy buddy = (Buddy) bundle.getSerializable("buddy");
				unreg(buddy);

			} else if ("stop".equals(action)) {
				running = false;
				this.stopSelf();
			}

		}

		return super.onStartCommand(intent, flags, startId);

	}

	// ////////util method////////////////////
	public static void start(Context ctx) {

		Intent intent = new Intent();
		intent.setAction(YoufangContext.CHAT_ATION);
		intent.putExtra("action", "start");
		intent.setClass(ctx, BuddyMessageService.class);
		ctx.startService(intent);

	}

	public static void reg(Context ctx, Buddy buddy) {

		Intent intent = new Intent();
		intent.setAction(YoufangContext.CHAT_ATION);
		intent.putExtra("buddy", buddy);
		intent.putExtra("action", "reg");
		intent.setClass(ctx, BuddyMessageService.class);
		ctx.startService(intent);

	}

	public static void unReg(Context ctx, Buddy buddy) {
		Intent intent = new Intent();
		intent.setAction(YoufangContext.CHAT_ATION);
		intent.putExtra("buddy", buddy);
		intent.putExtra("action", "unreg");
		intent.setClass(ctx, BuddyMessageService.class);
		ctx.startService(intent);

	}

	public static void stop(Context ctx) {

		Intent intent = new Intent();
		intent.setAction(YoufangContext.CHAT_ATION);
		intent.putExtra("action", "stop");
		intent.setClass(ctx, BuddyMessageService.class);
		ctx.startService(intent);

	}

}
